package com.lonely.system.engine.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lonely.common.core.domain.oss.MinIoParamBean;
import com.lonely.common.exception.BusinessException;
import com.lonely.common.utils.oss.MinIoUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;

/**
 * @author : 黄志标
 * @date: 2025/6/27 13:06
 * @description: minio 文件上传
 */
@Component
public class MinioFileUpload implements FileUploadInterface {

    @Autowired
    private MinIoParamBean minIoParamBean;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        String oldFileName = file.getOriginalFilename();
        Assert.isTrue(StrUtil.isNotBlank(oldFileName), "生成的文件的文件名为空");

        String fileName = String.format("%s.%s", IdUtil.randomUUID(), oldFileName.substring(oldFileName.lastIndexOf(".") + 1));

        // 使用minio api
        String filePath = String.format("uploads/%s", DateUtil.format(new Date(), "yyyyMM"));
        String remotePath = String.format("%s/%s", filePath, fileName);
        return MinIoUtil.uploadFile(this.minIoParamBean, fileName, file.getInputStream(), remotePath);
    }

    /**
     * 基于输入流上传文件
     *
     * @param inputStream
     * @param fileName
     * @return
     */
    @Override
    public String uploadStream(InputStream inputStream, String fileName) {
        if (inputStream == null) {
            throw new BusinessException("待上传到minio的输入流为空");
        }

        if (StrUtil.isBlank(fileName)) {
            throw new BusinessException("待上传到minio的文件名为空");
        }

        String filePath = String.format("uploads/%s", DateUtil.format(new Date(), "yyyyMM"));
        String remotePath = String.format("%s/%s", filePath, fileName);
        return MinIoUtil.uploadFile(this.minIoParamBean, fileName, inputStream, remotePath);
    }
}
